package comp.wxapi.utils;

import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import comp.wxapi.bean.LogoConfig;

public class QrcodeUtils {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(QrcodeUtils.class);
	
	public static final String DEFAULT_FORMAT = "png";
	
	private QrcodeUtils() {}
	
	public static void writeLogoIntoQrcode(BufferedImage image,InputStream logoInputStream,LogoConfig logoConfig,File output) {
		try {
			BufferedImage logo = ImageIO.read(logoInputStream);
	        Graphics2D g = image.createGraphics();
	        //考虑到logo照片贴到二维码中，建议大小不要超过二维码的1/5
	        int width = image.getWidth() / logoConfig.getLogoPart();
	        int height = image.getHeight() / logoConfig.getLogoPart();
	        //logo起始位置，此目的是为logo居中显示
	        int x = (image.getWidth() - width) / 2;
	        int y = (image.getHeight() - height) / 2;
	        //绘制图
	        g.drawImage(logo, x, y, width, height, null);
	        // 给logo画边框
	        // 构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke
	        g.setStroke(new BasicStroke(logoConfig.getBorder()));
	        g.setColor(logoConfig.getBorderColor());
	        g.drawRect(x, y, width, height);
	        g.dispose();
	        ImageIO.write(image, DEFAULT_FORMAT, output);
		} catch (Exception e) {
			LOGGER.error("ERROR:",e);
		}
	}
	
}
